package com.acargil.sudoku.view.listeners;

import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;

import com.acargil.sudoku.model.ISudokuEngine;
import com.acargil.sudoku.view.ISudokuView;
import com.acargil.sudoku.view.util.MessageFactory;

public class InputListener implements KeyListener {
    
	private static KeyListener instance = null;
    private ISudokuView view;
    private ISudokuEngine model;
    
    public static KeyListener getInstance(ISudokuView view, ISudokuEngine model) {
    	if (instance == null) {
			instance = new InputListener(view, model);
		}
    	
		return instance;
	}

    protected InputListener(ISudokuView view, ISudokuEngine model) {
        this.view = view;
        this.model = model;
    }

    public void keyTyped(KeyEvent e) { }

    public void keyPressed(KeyEvent e) {
        int keyCode = e.getKeyCode();

        if (keyCode <= 57 && keyCode > 48) {
            int x, y;
            x = view.getSelectedXIndex();
            y = view.getSelectedYIndex();
            model.setCellValue(x, y, keyCode - 48);
            checkGame();
            view.setAllCells(model.getAllCellValues());
        }
        else if(keyCode == KeyEvent.VK_DELETE) {
            int x, y;
            x = view.getSelectedXIndex();
            y = view.getSelectedYIndex();
            model.clearCellValue(x, y);
            checkGame();
            view.setAllCells(model.getAllCellValues());
        }
        else if(keyCode == KeyEvent.VK_DOWN) {
            view.shiftSelection(ISudokuView.SHIFT_DOWN);
        }
        else if(keyCode == KeyEvent.VK_UP) {
            view.shiftSelection(ISudokuView.SHIFT_UP);
        }
        else if(keyCode == KeyEvent.VK_RIGHT) {
            view.shiftSelection(ISudokuView.SHIFT_RIGHT);
        }
        else if(keyCode == KeyEvent.VK_LEFT) {
            view.shiftSelection(ISudokuView.SHIFT_LEFT);
        }
//        else
//            view.displayMessage("Invalid input for cell!", ISudokuView.ERROR_MESSAGE);
    }
    private void checkGame() {
        switch (model.checkStateOfGame()) {
		case VALID_STATE:
			
			break;
		case INVALID_STATE:
			model.takeBackLastMove();
//			view.displayMessage("Invalid move!", ISudokuView.ERROR_MESSAGE);
			break;
		case SUDOKU_SOLVED:
			MessageFactory.informationMessage("OK, YOU ARE DONE!");
			break;
		default:
			break;
		}
	}

	public void keyReleased(KeyEvent e) { }

}